/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.parsing;

/**
 * @author Clinton Begin
 */
public class GenericTokenParser {

  private final String openToken;
  private final String closeToken;
  private final TokenHandler handler;

  public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
    this.openToken = openToken;
    this.closeToken = closeToken;
    this.handler = handler;
  }

  public String parse(String text) {
    // 开始解析sql了, 这个类有两个参数openToken ,closeToken 在类实例化的时候传入,可以指定开始与结束的标识符
    //如:${} #{}
    if (text == null || text.isEmpty()) {
      return "";
    }
    // search open token
    int start = text.indexOf(openToken);
    if (start == -1) {
      return text;
    }
    // 如果找到#{ 或者 ${
    // 转成char数组
    char[] src = text.toCharArray();
    int offset = 0;
    final StringBuilder builder = new StringBuilder();
    StringBuilder expression = null;
    // do while 循环,判断条件是 存在下一个 ${ 或 #{
    do {
      if (start > 0 && src[start - 1] == '\\') {
        // this open token is escaped. remove the backslash and continue.
        // 这个开放令牌被转义。删除反斜杠并继续。
        builder.append(src, offset, start - offset - 1).append(openToken);
        offset = start + openToken.length();
      } else {
        // found open token. let's search close token.
        // 如果找到了${ 就让我们来寻找} 结束把;
        if (expression == null) {
          expression = new StringBuilder();
        } else {
          expression.setLength(0);
        }
        //第一次循环offset=0;start=${出现的位置
        builder.append(src, offset, start - offset);
        //重新赋值offset=${出现的位置+ ${ 的长度;
        offset = start + openToken.length();
        //查找结尾标记 };
        int end = text.indexOf(closeToken, offset);
        while (end > -1) {
          if (end > offset && src[end - 1] == '\\') {
            // this close token is escaped. remove the backslash and continue.
            expression.append(src, offset, end - offset - 1).append(closeToken);
            offset = end + closeToken.length();
            end = text.indexOf(closeToken, offset);
          } else {
            // 如果找到了结束标记,expression 从src数组中取出一段(offset 至 end 之间的数量 )追加上;
            // 也就是去除了 ${id},符号中包含的 id 字符串;
            String str=new String(src,offset,end-offset);
            expression.append(str);
            break;
          }
        }

        if (end == -1) {
          //如果没有找到} 结束标记,一般都能找到的.
          // close token was not found.
          builder.append(src, start, src.length - start);
          offset = src.length;
        } else {
          //这里调用 handler 的处理逻辑,去处理sql语句; 前面传的handle为
          //ParameterMappingTokenHandler.handleToken(); 直接返回了一个? 追加上;
          builder.append(handler.handleToken(expression.toString()));
          offset = end + closeToken.length();
        }
      }
      start = text.indexOf(openToken, offset);
    } while (start > -1);
    if (offset < src.length) {
      builder.append(src, offset, src.length - offset);
    }
    return builder.toString();
  }
}
